package com.innovate.nms.service.inspect;

import java.util.Calendar;

import javax.annotation.PostConstruct;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.Getter;
import lombok.Setter;

@Component
//@Log4j
public class InspectScheduler {
	
	@Getter
	private long lastTime = -1;
	
	@Getter
	private long nextTime = -1;
	
	@Setter @Getter
	private boolean forceOnce = false;
	
	@PostConstruct
	private void postConstruct() {
		
		calculateNextTaskTime();
		
	}

	@Scheduled(cron="* * *  * * ? ")   
    public void doScheduled() {
		
		long delta = millisecondsToNext();
		
		if(delta < 0 || forceOnce) {
			
			forceOnce = false;
			
			lastTime = System.currentTimeMillis();
			
			process();
			
			calculateNextTaskTime();
			
		} else {
						
			//log.info("Next schedule left " + (millisecondsToNext() / 1000) + " seconds");
			
		}
		
		
	}
	
	private void calculateNextTaskTime() {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR_OF_DAY, 1);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		nextTime = calendar.getTimeInMillis();
	}
	
	public long millisecondsToNext() {
		return nextTime - System.currentTimeMillis();
	}
	
	private void process() {
		InspectTasks.me.inspect();
	}

}
